<?php
namespace app\index\controller;
use EasyWeChat\Factory;
use think\Controller;

class Login extends Base
{
    public $openPlatform;
    public function __construct () {
        parent::__construct();
        $config = [
            'app_id'   => config('open_appid'),
            'secret'   => config('open_secret'),
            'token'    => config('open_token'),
            'aes_key'  => config('open_aeskey'),
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/index/login/wechat_callback',
            ]
        ];
        $this->openPlatform = Factory::openPlatform($config);
    }

    //微信登陆
    public function wechat(){
        $officialAccount = $this->openPlatform->officialAccount($this->mall['authorizer_appid'],$this->mall['authorizer_refresh_token']);
        $oauth = $officialAccount->oauth->scopes(['snsapi_userinfo']);
        if(session('user')) {
            header('Location: '.session('redirect_url'));exit;
        }
        return $oauth->redirect()->send();
    }

    //微信回调
    public function wechat_callback(){
        $officialAccount = $this->openPlatform->officialAccount($this->mall['authorizer_appid'],$this->mall['authorizer_refresh_token']);
          $user = $officialAccount->oauth->user()->toArray();
          session('user',$user);
          $wechatUser = $user['original'];
          $wechatUser['mall_id'] = $this->mall['id'];
          $user_id = $this->userModel->handleWechatUser($wechatUser);
          $this->userModel->login($user_id);
          header('Location: '.session('redirect_url'));exit;
    }

    public function index () {
        
    }
}
